<!--
 * @Descripttion: 技术后台（正式环境）指定对接项目
 * @version: 
 * @Author: zhangfan
 * @email: 2207044692@qq.com
 * @Date: 2021-04-13 10:28:50
 * @LastEditors: zhangfan
 * @LastEditTime: 2021-04-30 09:51:39
-->

<template>
  <div class="container" ref="mainCon">
    <div class="titleBox">
      <el-row class="topContent">
        <el-col :span="8">
          <i class="icon iconfont iconfanhui1" @click="goBack"></i>
          <span class="titleTop">指定对接项目</span>
        </el-col>
        <el-col :span="16" class="alignRight">
          <div>
            <el-link
              type="primary"
              v-if="isShowBtn"
              @click="downLoad('csSalaryExcel')"
            >
              下载模板
            </el-link>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="mainCon">
      <el-row class="detailInfo">
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-row class="searchBox searchInputWidth">
              <el-form :inline="true" :model="filterField" ref="accountForm">
                <el-col :lg="8" :xl="6">
                  <el-form-item label="项目名称" class="row-padding-bottom">
                    <el-input
                      placeholder="请输入"
                      clearable
                      v-model="filterField.projectName"
                    />
                  </el-form-item>
                </el-col>
                <el-form-item>
                  <el-button
                    type="primary"
                    icon="icon iconfont iconchazhao1"
                    @click="searchTable"
                    class="searchBtn"
                  >
                    <span>搜索</span>
                  </el-button>
                </el-form-item>
                <el-form-item>
                  <el-button
                    v-if="isShowBtn"
                    class="commonBut saveBtn funComBut"
                    icon="icon iconfont icontianjia"
                    @click="addItem"
                  >
                    <span class="opetareText">添加</span>
                  </el-button>
                </el-form-item>
                <el-form-item>
                  <el-button
                    v-if="isShowBtn"
                    class="commonBut saveBtn funComBut"
                    @click="toImportSalary"
                    >导入表格</el-button
                  >
                  <div class="upLoadDom" v-if="isShowBtn">
                    <form id="waterImportBox">
                      <input
                        type="file"
                        id="waterImportExcel"
                        name="file"
                        @change="waterImportfileChange"
                      />
                    </form>
                  </div>
                </el-form-item>
              </el-form>
            </el-row>
            <div class="spacing"></div>
            <!-- 表格 -->
            <div
              ref="tableBox"
              :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
            >
              <el-table
                ref="tableBox1"
                :max-height="tableHeight"
                :data="tableData"
                :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
                highlight-current-row
                stripe
                v-loading="loading"
                style="border: 1px solid #dfe6ec"
              >
                <el-table-column
                  align="center"
                  prop="areaName"
                  label="区域"
                  :formatter="formatTd"
                ></el-table-column>
                <el-table-column label="项目名称" width="230">
                  <template slot-scope="scope">
                    <copyText
                      :tableIndex="scope.$index"
                      :copyTextName="scope.row.projectName"
                      :columnName="'projectName'"
                    ></copyText>
                  </template>
                </el-table-column>
                <el-table-column label="施工方" width="230">
                  <template slot-scope="scope">
                    <copyText
                      :tableIndex="scope.$index"
                      :copyTextName="scope.row.pbName"
                      :columnName="'pbName'"
                    ></copyText>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="uscc"
                  label="施工方统一信用代码"
                  :formatter="formatTd"
                ></el-table-column>
                <el-table-column
                  v-if="isShowBtn"
                  align="center"
                  label="操作"
                  width="250px"
                  fixed="right"
                >
                  <template slot-scope="scope">
                    <div>
                      <el-link type="primary" @click="modifyItem(scope.row)"
                        >修改</el-link
                      >
                      <el-link type="danger" @click="handleDelete(scope.row.id)"
                        >删除</el-link
                      >
                    </div>
                  </template>
                </el-table-column>
                <div slot="empty" v-show="isShow">
                  <emptyTable emptyText="暂无相关信息"></emptyTable>
                </div>
              </el-table>
              <Pagination
                ref="pagination"
                @getList="getTableList"
                :requestUrl="requestUrl"
                :filterField="filterField"
              ></Pagination>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!--添加/修改项目-->
    <el-dialog
      :title="titleItem"
      :visible.sync="qpsVisible"
      :close-on-click-modal="false"
      @close="handleCloseQpsInput"
      custom-class="dialog-minwidth"
      width="650px"
      :modal-append-to-body="false"
    >
      <el-form
        :model="formData"
        ref="formRef"
        :rules="rules"
        label-width="150px"
      >
        <el-form-item label="区域" prop="addAreaId">
          <el-cascader
            class="optionWidth"
            v-model="addAreaId"
            :options="areasOptions"
            @change="getCostAreaId"
            clearable
            filterable
            placeholder="请选择"
            :props="{ checkStrictly: true }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            class="optionWidth"
            v-model="formData.projectName"
            placeholder="请输入项目名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="施工方" prop="pbName">
          <el-input
            class="optionWidth"
            v-model="formData.pbName"
            placeholder="请输入施工方"
          ></el-input>
        </el-form-item>
        <el-form-item label="施工方统一信用代码" prop="uscc">
          <el-input
            class="optionWidth"
            v-model="formData.uscc"
            placeholder="请输入施工方统一信用代码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleCloseQpsInput" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="toSaveQpsInput('formRef')"
          class="save"
          :loading="canLogin"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import common from '../../kits/common'
import scrollTable from '@/mixin/scrollTable.js'

export default {
  name: 'designatedItemJs',
  mixins: [scrollTable],
  data() {
    var checkArea = (rule, value, callback) => {
      if (!this.addAreaId || this.addAreaId.length < 1) {
        return callback(new Error('请选择区域'))
      } else {
        callback()
      }
    }
    return {
      projectInfo: {},
      formArea: '',
      addAreaId: '',
      titleItem: '添加项目',
      requestUrl: '/api-m/inputUserAuthData/base/v1/page', //表格请求路径
      filterField: {
        projectName: '',
        authId: '',
      },
      formData: {
        authId: '',
        areaId: '',
        projectName: '',
        pbName: '',
        uscc: '',
      },
      rules: {
        addAreaId: [
          {
            required: true,
            validator: checkArea,
            trigger: 'change',
          },
        ],
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' },
        ],
        pbName: [{ required: true, message: '请输入施工方', trigger: 'blur' }],
        uscc: [
          {
            required: true,
            message: '请输入施工方统一信用代码',
            trigger: 'blur',
          },
        ],
      },
      tableData: [],
      canLogin: false,
      calcTypeList: [],
      industryOptions: [],
      loading: false,
      isShow: false,
      qpsVisible: false,
      isShowBtn: true,
      type: '',
      typePage: '',
      flieUpload: {
        authId: '',
      },
    }
  },
  computed: { ...mapState(['areasOptions']) },
  created() {
    this.typePage = this.$route.query.typePage
    if (this.$route.query.typePage == 'jscs') {
      this.isShowBtn = false
    } else {
      this.isShowBtn = true
    }
    //获取区域
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.authId = this.$route.query.authId
    this.filterField.authId = this.$route.query.authId
    this.flieUpload.authId = this.$route.query.authId
    this.formData.authId = this.$route.query.authId
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  methods: {
    /**
     * @description: 下载项目导入模板
     * @param {*} type
     */
    downLoad(type) {
      this.axios({
        method: 'post',
        url: 'api-f/files/ipuntprojecttemplate',
      })
        .then((response) => {
          if (!response.data.hasError) {
            window.open(response.data.result.url)
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg,
            })
          }
        })
        .catch((error) => {})
    },
    ...mapActions(['getAreas']),
    getCostAreaId() {
      let areaId = this.addAreaId[this.addAreaId.length - 1]
      this.formData.areaId = areaId
    },
    /**
     * @description: 删除项目
     */
    handleDelete(id) {
      this.$confirm(
        '删除后用户将无法上传/查询该项目的数据，是否确认删除?',
        '提示',
        {
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning',
        }
      )
        .then(() => {
          this.toDel(id)
        })
        .catch(() => {})
    },
    toDel(id) {
      this.axios({
        method: 'post',
        url: 'api-m/inputUserAuthData/base/v1/delete',
        data: {
          id: id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$nextTick(function () {
                this.$refs.pagination.getTableListData()
              })
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    /**
     * @description: 导入表格
     * @param {*} e
     */
    waterImportfileChange(e) {
      var that = this
      var url = window.location.href
      var Filedata = $('#waterImportExcel').val()
      var files = e.target.files[0]
      if (!/\.(xls|xlsx)$/.test(Filedata)) {
        this.$message({
          message: 'excel类型必须是.xls,xlsx中的一种',
          type: 'warning',
        })
        return
      }

      setTimeout(function () {
        that.uploadFileByAjaxSubmit(
          'api-m/inputUserAuthData/base/v1/import',
          that.success,
          that.error
        )
      }, 500)
    },
    uploadFileByAjaxSubmit(url, successCallBack, errorCallBack) {
      const vm = this
      var token = localStorage.getItem('access_token')
      var options = {
        url: common.uploadUrl + url,
        type: 'POST',
        data: vm.flieUpload,
        headers: { Authorization: 'Bearer ' + token },
        contentType: false,
        processData: false,
        success: function (data) {
          $('#waterImportExcel').val('')
          successCallBack(data)
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          $('#waterImportExcel').val('')
          errorCallBack(XMLHttpRequest, textStatus, errorThrown)
        },
      }

      //三种方式均可
      $('#waterImportBox').ajaxSubmit(options)
      return false
    },
    success(data) {
      if (!data.hasError) {
        this.$message({
          message: data.msg,
          type: 'success',
        })
        this.$nextTick(function () {
          this.$refs.pagination.getTableListData()
        })
      } else {
        this.errorNotice = data.errorMsg
        this.formVisible = true
      }
    },
    //根据状态码判断是否是401
    error(XMLHttpRequest, textStatus, errorThrown) {
      if (XMLHttpRequest.status === '401' || XMLHttpRequest.status === '403') {
        localStorage.setItem('access_token', '')
        localStorage.setItem('refresh_token', '')
        localStorage.setItem('userName', '')
        // 只有在当前路由不是登录页面才跳转
        if (router.currentRoute.path !== '/login/loginFirst') {
          router.replace({
            path: '/login/loginFirst',
          })
        }
        //清除tab栏数据
        this.$store.state.sliderBar = []
        localStorage.removeItem('sliderBar')
      } else {
        this.$message({
          message: '数据请求失败',
          type: 'warning',
        })
      }
    },
    /**
     * @description: 添加项目
     */
    addItem() {
      const vm = this
      vm.qpsVisible = true
      vm.formData.areaId = ''
      vm.formData.projectName = ''
      vm.formData.pbName = ''
      vm.formData.uscc = ''
      vm.addAreaId = ''
      vm.titleItem = '添加项目'
      this.$nextTick(function () {
        this.$refs.formRef.resetFields()
      })
    },
    /**
     * @description: 修改项目
     */
    modifyItem(row) {
      const vm = this
      vm.titleItem = '修改项目'
      vm.qpsVisible = true
      vm.formData.authId = row.authId
      vm.formData.areaId = row.areaId
      vm.formData.id = row.id
      vm.formData.projectName = row.projectName
      vm.formData.pbName = row.pbName
      vm.formData.uscc = row.uscc
      vm.addAreaId = row.areaId
      vm.type = 'modify'
    },
    /**
     * @description: 保存添加项目
     */
    toSaveQpsInput(formName) {
      const vm = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.canLogin = true
          vm.addAppidItem()
        } else {
          return false
        }
      })
    },
    /**
     * @description: 添加项目
     */
    addAppidItem() {
      const vm = this
      let urlAppid = ''
      if (vm.type == 'modify') {
        urlAppid = 'api-m/inputUserAuthData/base/v1/update'
      } else {
        urlAppid = 'api-m/inputUserAuthData/base/v1/add'
      }
      this.axios({
        method: 'post',
        data: vm.formData,
        url: urlAppid,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              vm.qpsVisible = false
              this.$refs.pagination.getTableListData()
              this.canLogin = false
              if (vm.type == 'modify') {
                this.$message({
                  message: '修改成功',
                  type: 'success',
                })
              } else {
                this.$message({
                  message: '添加成功',
                  type: 'success',
                })
              }
            } else {
            }
          },
          (response) => {
            this.canLogin = false
          }
        )
        .catch((error) => {
          this.canLogin = false
        })
    },
    /**
     * @description: 关闭添加项目弹框
     */
    handleCloseQpsInput() {
      const vm = this
      vm.qpsVisible = false
    },
    getTableList(data) {
      this.tableData = data
      this.loading = false
      if (this.tableData.length < 1) {
        this.isShow = true
      }
    },
    //列表查询
    searchTable() {
      this.$refs.pagination.getTableListData()
    },
    goBack() {
      if (this.typePage == 'jszs') {
        this.$router.push('/home/interfacePlatform/equipmentAppidJs')
        this.$store.commit('CHANGE_SLIDER_NAME', {
          oldUrl: '/home/interfacePlatform/equipmentAppidJs',
          newUrl: this.$router.currentRoute.fullPath,
        })
      } else {
        this.$router.push('/home/interfacePlatform/equipmentAppidJsCs')
        this.$store.commit('CHANGE_SLIDER_NAME', {
          oldUrl: '/home/interfacePlatform/equipmentAppidJsCs',
          newUrl: this.$router.currentRoute.fullPath,
        })
      }
    },
  },
}
</script>
<style scoped lang="less">
.topTitle {
  height: 67px;
  background-color: #e4ebf1;
  padding-left: 24px;
  font: bold 18px/67px Microsoft YaHei;
}
.mainCon {
  top: 194px;
}

.blockquote {
  color: #333;
  font: bold 16px Microsoft YaHei;
  border-bottom: 1px solid #dee5f4;
  height: 35px;
}

.blockquote:before {
  background-color: #009588;
  content: '';
  padding: 2px;
  margin-right: 10px;
}

.labelWidth {
  width: 126px;
  font-size: 14px;
  color: #666666;
  display: inline-block;
  height: 36px;
  text-align: right;
}

.information {
  font-size: 14px;
  color: #151515;
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.detailInfo {
  padding: 0 0 5px 0;
}

.detailInfoItem {
  margin-top: 28px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.tag-item {
  color: #ffffff !important;
  font-size: 12px;
  border-radius: 0px;
  height: 20px;
  line-height: 18px;
  width: 60px;
  margin-left: 12px;
}
.titleBox {
  padding: 0 24px;
  background-color: #fff;
}
.topContent {
  border-bottom: 1px solid #e3e7e9;
  height: 52px;
  line-height: 52px;
  .el-col {
    line-height: 52px;
  }
  .titleTop {
    font: bold 18px Microsoft YaHei;
    color: #333333;
  }
  .alignRight {
    text-align: right;
    .el-link {
      line-height: 24px;
    }
  }
  .salaryAccountBut {
    padding: 10px 23px;
  }
}
.upLoadDom {
  position: absolute;
  width: 96px;
  height: 36px;
  top: 0;
  left: 0;
  opacity: 0;
  line-height: 0px;
  form {
    input {
      width: 96px;
      height: 36px;
      line-height: 0px;
      cursor: pointer;
    }
  }
}
@import '../../../static/css/filterArea.less';
</style>
